// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.

const {SerialPort} = require('serialport');
const { ReadlineParser } = require('@serialport/parser-readline')
const tableify = require('tableify')
var port;
var serialflage=0;

async function listSerialPorts() {
 
SerialPort.list().then(ports => {
       ports.forEach(port => {
       
 port = new SerialPort({
  path:  port.path,
  baudRate: 115200,
  autoOpen: false,
})

port.open(err => {
		       console.log('IsOpen: ', port.isOpen);
		       console.log('Err: ', err);
		       if (err) {
		       }
		   });

  port.close(error => {
  serialflage=0;
     console.log('close: ');
  })  
const parser = port.pipe(new ReadlineParser({ delimiter: '\r\n' }))
parser.on('data',function(data){
  
	if(typeof(data) == "undefined") {
			console.log("11111");
			return;
		}
		if((data.substr(0, 1) != '{')&&(data.substr(-1) != '}') ) {

			return;
		}
    serialflage=1;
    console.log(JSON.parse(data));
    });
  });
})

}

//做一个定时器   检测串口的数据，如果没有，则	
 var t1= setInterval(function(){	
if(serialflage==1){
	//正常
	console.log("serial true");
}
	else{
			listSerialPorts();
			console.log("serial false");
		}
		
	serialflage=0;	
		

 },5000);	


listSerialPorts()
